#include <WiFi.h>

#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>

const char* ssid;
const char* password;

// WiFi
WiFiClient espClient;

//启用webserver

BLEServer *pServer = NULL;
BLECharacteristic *pCharacteristic = NULL;
bool deviceConnected = false;

// 蓝牙服务和特征 UUID
#define SERVICE_UUID        "12345678-1234-1234-1234-123456789012"
#define CHARACTERISTIC_UUID "87654321-4321-4321-4321-210987654321"


// 蓝牙回调函数，处理 Wi-Fi 凭证的接收
class MyCallbacks: public BLECharacteristicCallbacks {
  void onWrite(BLECharacteristic *pCharacteristic) {
    std::string value = pCharacteristic->getValue();
    if (value.length() > 0) {
      // 解析 Wi-Fi SSID 和密码
      sscanf(value.c_str(), "%s %s", ssid, password);
      deviceConnected = true;
    }
  }
};


///////////////////////////////////////////////////////////
void setup() {
  Serial.begin(115200);

  // 初始化蓝牙
  BLEDevice::init("ESP32_BLE_Provisioning");
  pServer = BLEDevice::createServer();
  BLEService *pService = pServer->createService(SERVICE_UUID);
  pCharacteristic = pService->createCharacteristic(
                      CHARACTERISTIC_UUID,
                      BLECharacteristic::PROPERTY_WRITE);
  pService->start();
  BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();
  pAdvertising->start();
  Serial.println("Waiting for BLE client to send WiFi credentials...");

  // 等待蓝牙客户端连接并写入 Wi-Fi 信息
  while (!deviceConnected) {
    delay(1000);
  }
  Serial.println("BLE client connected, credentials received");

  // 尝试连接 WiFi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");

}

void loop() {
  //

}

